import "./mongoose/index";
import * as express from "express";
import * as bodyParser from "body-parser";
import { Routes } from "./routes";
import { Request, Response, NextFunction } from "express";
import { mongooseErrorHandler } from "./middleware/MongooseError.middleware";
import { mongoErrorHandler } from "./middleware/Mongo.middleware";

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

Routes.forEach((route) => {
  (app as any)[route.method](
    route.route,
    (req: Request, res: Response, next: Function) => {
      const result = new (route.controller as any)()[route.action](
        req,
        res,
        next
      );
      if (result instanceof Promise) {
        result.then((result) =>
          result !== null && result !== undefined ? res.send(result) : undefined
        );
      } else if (result !== null && result !== undefined) {
        res.json(result);
      }
    }
  );
});

app.use(mongooseErrorHandler);
app.use(mongoErrorHandler);
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  console.error(err);
  res.status(500).json({ statusCode: 500, message: "Internal Server Error" });
});

app.listen(3000);
console.log(
  "Express server has started on port 3000. Open http://localhost:3000 to see results"
);
